<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="filter">
          <el-form-item label="文章分类">
            <el-select v-model="filter.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="filter.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="initArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubDialogVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-dialog title="发表文章" :visible.sync="pubDialogVisible" fullscreen :before-close="handleClose" @closed="onDialogClosed">
        <!-- 文章内容 -->
        <!-- 文章标题 -->
        <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
          </el-form-item>
          <!-- 文章分类 -->
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!-- 文本编辑器 -->
          <el-form-item label="文章内容" prop="content">
            <!-- 使用 v-model 进行双向的数据绑定 -->
            <quill-editor v-model="pubForm.content" @blur="$refs.pubFormRef.validateField('content')"></quill-editor>
          </el-form-item>

          <!-- 文章封面 -->
          <el-form-item label="文章封面" prop="cover_img">
            <!-- 用来显示封面的图片 -->
            <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef" />
            <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="onCoverChange" />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="cImg">+ 选择封面</el-button>
          </el-form-item>

          <!-- 发布和草稿 -->
          <el-form-item>
            <el-button type="primary" @click="add('已发布')">发布</el-button>
            <el-button type="info" @click="add('草稿')">存为草稿</el-button>
          </el-form-item>

        </el-form>
      </el-dialog>
      <!-- 分页区域 -->

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="scope">
            <el-link type="primary" @click="showDetail(scope.row.id)">{{scope.row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="scope" prop="pub_date">
            {{formatDate(scope.row.pub_date)}}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="danger" size="mini" @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="q.pagenum" :page-sizes="[2, 3, 5, 10]" :page-size="q.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 查看文章详情的对话框 -->
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>
        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{formatDate(artDetail.pub_date)  }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        <!-- 分割线 -->
        <el-divider></el-divider>
        <!-- 文章的封面 -->
        <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />
        <!-- 文章的详情 -->
        <div v-html="artDetail.content" class="detail-box"></div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubDialogVisible: false, //发表文章弹窗
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择图片', trigger: 'click' }]
      },
      //文章分类列表
      cateList: [],
      //接收图片的url
      preview: '',
      //发布和草稿
      artList: [],
      total: 0,
      //筛选
      filter: {
        cate_id: '',
        state: ''
      },
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false,
      // 文章的详情信息对象
      artDetail: {}
    }
  },
  methods: {
    //点击发表文章 弹出窗口
    handleClose (done) {
      this.$confirm('此操作将退出, 是否继续?', {
        type: 'warning'
      })
        .then(_ => {
          done();
        })
        .catch(_ => { })

      this.$refs.pubFormRef.resetFields()
      this.preview = ''
    },
    //发送axios获取文章分类数据 并循环渲染分类
    async getCateList () {
      const { data: res } = await this.$http('/my/cate/list')
      if (res.code !== 0) return
      this.cateList = res.data
    },
    //点击选择封面触发input文件选择框
    cImg () {
      this.$refs.iptFileRef.click()
    },
    //触发change事件
    onCoverChange (e) {
      const file = e.target.files[0]
      if (file) {
        this.pubForm.cover_img = file
        this.preview = URL.createObjectURL(file)
      } else {
        this.pubForm.cover_img = ''
        this.preview = ''
      }
      this.$refs.pubFormRef.validateField('cover_img') //校验图片
    },
    //发布和草稿
    add (state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(async valid => {
        if (!valid) return
        const fd = new FormData
        for (let k in this.pubForm) {
          fd.append(k, this.pubForm[k])
        }
        const { data: res } = await this.$http.post('/my/article/add', fd)

        if (res.code !== 0) return this.$message.error(res.message)

        this.$message.success(res.message)

        this.pubDialogVisible = false

        this.getCateList()
      })
    },
    //关闭窗口后重置表单数据
    onDialogClosed () {
      this.$refs.pubFormRef.resetFields()
      this.preview = ''
    },
    //发送axios获取列表数据
    async getArtList () {
      const { data: res } = await this.$http('/my/article/list', { params: { ... this.q } })
      if (res.code !== 0) return
      this.artList = res.data
      this.total = res.total
    },
    //定义一个格式化时间函数dayjs
    formatDate (vla) {
      return dayjs(vla).format('YYYY-MM-DD HH:mm:ss');
    },
    handleSizeChange (psize) {
      this.q.pagesize = psize
      this.getArtList()
    },
    handleCurrentChange (pnum) {
      this.q.pagenum = pnum
      this.getArtList()
    },
    //筛选
    initArtList () {
      this.q.cate_id = this.filter.cate_id
      this.q.state = this.filter.state
      this.getArtList()
    },
    //重置
    resetList () {
      this.filter.cate_id = ''
      this.filter.state = ''
      this.q.pagenum = 1
      this.q.pagesize = 2
      this.getArtList()
    },
    //删除
    remove (id) {
      this.$confirm('此操作将删除, 是否继续?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('/my/article/info', { params: { id } })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)

        //防止出现暂无数据
        if (this.artList.length === 1 && this.q.pagenum > 1) {
          this.q.pagenum--
        }

        this.getArtList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //点击文章标题弹出详情数据
    async showDetail (id) {
      const { data: res } = await this.$http('/my/article/info', { params: { id } })
      if (res.code !== 0) return
      this.artDetail = res.data
      this.detailVisible = true
    }
  },
  created () {
    this.getCateList()
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度  /deep/深度选择器
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
